﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;

namespace _078.内存缓存.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly IMemoryCache memoryCache;
        private readonly ILogger<TestController> logger;


        public TestController(IMemoryCache memoryCache, ILogger<TestController> logger)
        {
            this.memoryCache = memoryCache;
            this.logger = logger;
        }

        /*
         * 不使用内存缓存
         */
        [HttpGet]
        public ActionResult<Book> GetBookById(long id)
        {
            Book? result = MyDbContext.GetById(id);
            if (result == null)
            {
                return NotFound($"找不到id={id}的书");
            }
            else
            {
                return result;
            }
        }

        /*
         * 使用缓存\
         *  缓存中有的话就用缓存中的
         */
        [HttpGet]
        public async Task<ActionResult<Book?>> GetBookById2(long id)
        {
            await Console.Out.WriteLineAsync("开始执行GetBooks");
            Book? result = await memoryCache.GetOrCreateAsync("Book" + id, async (e) =>
            {
                await Console.Out.WriteLineAsync("从数据库中读取数据");
                // 设置过期时间为10秒 超过十秒缓存失效  绝对过期策略
                //e.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10);

                // 滑动过期策略 只要在缓存没过期的时候请求一次 缓存自动续命一段时间
                e.SlidingExpiration = TimeSpan.FromSeconds(10);
                return await MyDbContext.GetByIdAsync(id);
            });
            await Console.Out.WriteLineAsync($"GetOrCreateAsync结果{result}");
            if (result == null)
            {
                return NotFound($"找不到id={id}的书");
            }
            else
            {
                return result;
            }
        }
    }
}
